package com.hp.myoauthdemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hp.myoauthdemo.constants.OauthConstant;
import com.hp.myoauthdemo.model.OauthParams;
import com.hp.myoauthdemo.utils.HttpClientUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Oauth相关
 *
 * @author hupan
 * @date 2019-08-27 14:49
 */
@Controller
@RequestMapping("/oauth")
public class OauthController {

    @GetMapping("/request")
    public String request() {
        return "redirect:" + OauthConstant.authorizeUrl + "?client_id=" + OauthConstant.clientId + "&redirect_uri=" + OauthConstant.redirectUrl;
    }

    @GetMapping("/redirect")
    public String redirect(final String code) {
        return "redirect:get/token?code=" + code;
    }

    @GetMapping("/get/token")
    public ModelAndView getToken(final String code, final ModelAndView modelAndView) {
        OauthParams params = new OauthParams();
        params.setClientId(OauthConstant.clientId);
        params.setClientSecret(OauthConstant.clientSecret);
        params.setCode(code);

        String result = HttpClientUtil.doPostJson(OauthConstant.getTokenUrl, JSON.toJSONString(params));
        modelAndView.setViewName("token");
        modelAndView.addObject("token", result);

        return modelAndView;
    }

}
